package com.xxwy.trie.practice.leetcode;

import java.util.TreeMap;

/**
 * @author xxwy
 * 677
 */
public class MapSum {

    private class Node{
        int val;
        TreeMap<Character, Node> next;

        public Node(int val) {
            this.val = val;
            next = new TreeMap<>();
        }
        public Node() {
            this.val = 0;
            next = new TreeMap<>();
        }
    }

    private Node root;


    /** Initialize your data structure here. */
    public MapSum() {
        root = new Node();
    }

    public void insert(String key, int val) {
        Node cur = root;
        for (int i = 0; i < key.length(); i++) {
            char c = key.charAt(i);
            if(cur.next.get(c) == null){
                cur.next.put(c,new Node());
            }
            cur = cur.next.get(c);
        }
        cur.val = val;
    }

    public int sum(String prefix) {
        Node cur = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null){
                return 0;
            }
           cur = cur.next.get(c);
        }

        //cur是当前prefix的最后一个char的结点
        return sum(cur);


    }

    private int sum(Node node){
        int res = node.val;
        for (char nextChar : node.next.keySet()) {
            res+=sum(node.next.get(nextChar));
        }
        return res;
    }
}
